const express = require("express");
const joi = require("joi");

const app = express();

const cors = require("cors");
app.use(cors());

app.use(express.json());
app.use(express.urlencoded({ extended: false }));

app.use((req, res, next) => {
  res.cc = (err, RetCode = -1, RetObject = undefined) => {
    res.send({
      RetCode,
      RetMessage: err instanceof Error ? err.message : err,
      RetObject,
    });
  };
  next();
});

const { expressjwt: expressJWT } = require("express-jwt");
const config = require("./config");

app.use(
  expressJWT({ secret: config.jwtSecretKey, algorithms: ["HS256"] }).unless({
    path: [/^\/user\//],
  })
);

// 导入登录相关路由
const userRouter = require("./router/user");
app.use("/user", userRouter);

// 定义错误级别的中间件
app.use((err, req, res, next) => {
  // 验证失败导致的错误
  if (err instanceof joi.ValidationError) return res.cc(err);
  // 身份认证失败的错误
  if (err.name === "UnauthorizedError") return res.cc("身份认证失败！");
  // 未知的错误
  res.cc(err);
});

app.listen("88", () => {
  console.log("Server running at http://127.0.0.1:88");
});
